import Vue from "vue";
import VueRouter from "vue-router";
//引入封装好的仓库模块
import store from "../store";
/* 
封装一个函数，用来检测你是否含有当前地址的访问权
*/
function hasUrl(path, next) {
  let result = store.state.userinfo.menus_url.find((item) => item == path);
  if (result) {
    next();
  } else {
    next("/home");
  }
}

Vue.use(VueRouter);

export const indexRoutes = [
  {
    path: "/menu",
    component: () => import("../views/menu/menu.vue"),
    meta: {
      title: "菜单管理",
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/menu", next);
    },
  },
  {
    path: "/role",
    component: () => import("../views/role/role.vue"),
    meta: {
      title: "角色管理",
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/role", next);
    },
  },
  {
    path: "/manger",
    component: () => import("../views/manger/manger.vue"),
    meta: {
      title: "管理员管理",
    },
    beforeEnter: (to, from, next) => {
      hasUrl("/manger", next);
    },
  },
  {
    path: "/cates",
    component: () => import("../views/goodscate/goodscate.vue"),
    meta: {
      title: "商品分类",
    },
  },
  {
    path: "/specs",
    component: () => import("../views/goodsspecs/goodsspecs.vue"),
    meta: {
      title: "商品规格",
    },
  },
  {
    path: "/goods",
    component: () => import("../views/goods/goods.vue"),
    meta: {
      title: "商品管理",
    },
    
  },

  {
    path: "/banner",
    component: () => import("../views/banners/banners.vue"),
    meta: {
      title: "轮播图管理",
    },
  },

  {
    path: "/member",
    component: () => import("../views/member/members.vue"),
    meta: {
      title: "会员管理",
    },
  },

  {
    path: "/seck",
    component: () => import("../views/seckill/seckills.vue"),
    meta: {
      title: "秒杀活动",
    },
  },
];

const routes = [
  {
    path: "/login",
    component: () => import("../pages/login.vue"),
  },
  {
    path: "/index",
    component: () => import("../pages/index.vue"),
    children: [
      {
        path: "/home",
        component: () => import("../views/home.vue"),
      },
      ...indexRoutes,
      {
        path: "",
        redirect: "/home",
      },
    ],
  },
  {
    path: "*",
    redirect: "/index",
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

//封装一个登录拦截事件，利用全局路由导航守卫之前置导航钩子函数
router.beforeEach((to, from, next) => {
  //一、看访问地址是否为登录，如果是就next
  if (to.path == "/login") {
    next();
    return;
  }
  //二、是否存在登录信息（通过检查是否含有离线存储）
  if (store.state.userinfo) {
    next();
    return;
  }
  //三、以上条件都不符合 强制它跳转到登录页
  next("/login");
});

export default router;
